//
//  ViewController.m
//  下载Word并打开
//
//  Created by 徐鲤鸿 on 2019/4/17.
//  Copyright © 2019 中创慧谷. All rights reserved.
//

#import "ViewController.h"

#import "AFNetworking/AFNetworking/AFNetworking.h"
#import "SVProgressHUD/SVProgressHUD/SVProgressHUD.h"

/// 下载地址
#define downloadString @"https://alicliimg.clewm.net/000/137/5137000/15554088378552e5d546734d5101d0d94dd74b62d8aa71555408808.docx"

@interface ViewController ()<UIDocumentInteractionControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor greenColor];
    
    UIButton * downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:downloadBtn];
    downloadBtn.backgroundColor = [UIColor redColor];
    [downloadBtn setTitle:@"下载/打开" forState:UIControlStateNormal];
    downloadBtn.frame = CGRectMake(50, 50, 100, 50);
    [downloadBtn addTarget:self action:@selector(downloadAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:deleteBtn];
    deleteBtn.backgroundColor = [UIColor redColor];
    [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    deleteBtn.frame = CGRectMake(200, 50, 100, 50);
    [deleteBtn addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
}

/// 下载/打开
- (void)downloadAction{
    NSString * str = downloadString;
    NSString * suffix = [str pathExtension];
    NSString * name = [NSString stringWithFormat:@"文件.%@", suffix];
    [self openDocxWithName:name];
}
/// 删除
- (void)deleteAction{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths lastObject];
    NSString * path = [documentsDirectory stringByAppendingPathComponent:@"/files"];
    [fileManager removeItemAtPath:path error:nil];
}

- (void)openDocxWithName:(NSString *)docPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths lastObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString * filesPath = [documentsDirectory stringByAppendingPathComponent:@"files"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filesPath]) {
        /// 创建一个文件
       BOOL success =  [[NSFileManager defaultManager] createDirectoryAtPath:filesPath withIntermediateDirectories:YES attributes:nil error:nil];
        NSLog(@"success:%d", success);
    }
    
    NSString *filePath = [filesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", docPath]];
    if ([fileManager fileExistsAtPath:filePath]) {
        //文件已经存在,直接打开
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:cancelAction];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self openDocxWithPath:filePath];
        }]];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else {
        //文件不存在,要下载
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否下载并打开打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:cancelAction];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self downloadDocxWithDocPath:filesPath fileName:docPath];
        }]];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
}
/**
 下载文件
 
 @param docPath 文件路径
 @param fileName 文件名
 */
-(void)downloadDocxWithDocPath:(NSString *)docPath fileName:(NSString *)fileName {
    
    NSString *urlString = downloadString;
    NSURL * url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        NSLog(@"%lld   %lld",downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
        NSLog(@"下载中....");
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *path = [docPath stringByAppendingPathComponent:fileName];
        return [NSURL fileURLWithPath:path];  //这里返回的是文件下载到哪里的路径 要注意的是必须是携带协议file://
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        NSString *name = [filePath path];
        [self openDocxWithPath:name];
    }];
    [task resume];
    
}
/**
 打开文件
 
 @param filePath 文件路径
 */
-(void)openDocxWithPath:(NSString *)filePath {
    NSLog(@"%s", __func__);
    UIDocumentInteractionController *doc= [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
    doc.delegate = self;
    [doc presentPreviewAnimated:YES];
    // 打开的过程有点慢
}

//必须实现的代理方法 预览窗口以模式窗口的形式显示，因此需要在该方法中返回一个view controller ，作为预览窗口的父窗口。如果你不实现该方法，或者在该方法中返回 nil，或者你返回的 view controller 无法呈现模式窗口，则该预览窗口不会显示。
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    NSLog(@"%s", __func__);
    
    return self;
}

- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller {
    NSLog(@"%s", __func__);
    
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {
    NSLog(@"%s", __func__);
    
    return CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height);
}


@end
